// g-cache main package

package main

import (
	"flag"
	"log"
	"net/http"
	"strings"

	"github.com/cloudwego/hertz/pkg/app/server"

	router "g-cache/biz/router"
	"g-cache/pkg/cache"
)

var (
	port    = flag.String("port", "8001", "Geecache server port")
	apiPort = flag.String("api", "8889", "API server port")
	peers   = flag.String("peers", "", "Comma-separated list of peer URLs")
)

func main() {
	flag.Parse()

	// 初始化缓存组
	initCacheGroup()

	// 初始化HTTP池并设置节点
	self := "http://localhost:" + *port
	httpPool := NewHTTPPool(self)
	httpPoolInstance = httpPool

	// 解析并设置peer节点
	if *peers != "" {
		peerList := strings.Split(*peers, ",")
		httpPool.Set(peerList...)
		log.Printf("节点 %s 已注册到集群，peer列表: %v", self, peerList)
	}

	// 注册HTTP处理器
	go func() {
		log.Printf("缓存服务运行在 %s", self)
		if err := http.ListenAndServe(":"+*port, httpPool); err != nil {
			log.Fatalf("缓存服务启动失败: %v", err)
		}
	}()

	// 创建hertz API服务器
	h := server.Default(server.WithHostPorts(":" + *apiPort))

	// 注册路由
	router.GeneratedRegister(h)

	log.Printf("API服务器运行在 http://localhost:%s", *apiPort)
	h.Spin()
}

func initCacheGroup() {
	// 创建一个缓存组作为示例
	gc := cache.NewGroup("scores", 2<<10, cache.GetterFunc(
		func(key string) ([]byte, error) {
			log.Printf("load key %s from database", key)
			return []byte(key), nil
		},
	))

	// 设置peerPicker以支持分布式缓存
	if httpPool := getHTTPPool(); httpPool != nil {
		gc.RegisterPeers(httpPool)
	}
}

// 全局HTTP池实例
var httpPoolInstance *HTTPPool

// getHTTPPool 返回全局HTTP池实例
func getHTTPPool() *HTTPPool {
	return httpPoolInstance
}
